import os
import smtplib
import sys
from email.mime.application import MIMEApplication
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header


def send_email(smtp_server, sender_name, from_mail, mail_pass, to_mails, subj, body, attachment=None):
    msg = MIMEMultipart()
    msg['From'] = Header(sender_name, 'utf-8')
    msg['To'] = to_mails
    msg['Subject'] = Header(subj, 'utf-8')
    msg.attach(MIMEText(body, 'plain', 'utf-8'))

    if attachment and os.path.exists(attachment):
        with open(attachment, 'rb') as f:
            mime = MIMEApplication(f.read())
            mime.add_header('Content-Disposition', 'attachment', filename=attachment)
            msg.attach(mime)
    try:
        s = smtplib.SMTP()
        s.connect(smtp_server, 25)
        s.login(from_mail, mail_pass)
        s.sendmail(from_mail, to_mails.split(','), msg.as_string())
        s.quit()
        print('发送成功')
    except Exception as e:
        print(f'Error: {e}')


def main():
    if len(sys.argv) < 8:
        print("参数错误")
        return

    smtp_server = sys.argv[1]
    sender_name = sys.argv[2]
    from_mail = sys.argv[3]
    mail_pass = sys.argv[4]
    to_mails = sys.argv[5]
    subj = sys.argv[6]
    body = sys.argv[7]
    attach_file = ''
    if len(sys.argv) > 8:
        attach_file = sys.argv[8]
    send_email(smtp_server, sender_name, from_mail, mail_pass, to_mails, subj, body, attach_file)


if __name__ == '__main__':
    main()
